//
//  NextLevelScene.m
//  z_boxem
//
//  Created by A B on 2/5/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "NextLevelScene.h"
#import "HelloWorldLayer.h"
#import "CCUIViewWrapper.h"
#import "Score.h"
@implementation NextLevelScene


+(id) sceneWith:(int)score:(int) moves:(int) level{    
    CCScene *scene = [CCScene node];    
    NextLevelScene *layer = [[NextLevelScene alloc]initWith:score:moves:level]; 
    [scene addChild: layer];    
    return scene;
}
int currentLevel;
int currentScore;
CCUIViewWrapper *wrapper;
-(id) initWith:(int) score:(int) moves: (int) level
{
    
    if( (self=[super init] )) {
        CCLabelTTF *title = [CCLabelTTF labelWithString:@"You won" fontName:@"Courier" fontSize:64];
        title.position =  ccp(240, 280);
        [self addChild: title];
        
        currentLevel = level;
        currentScore = score + MAX(50-moves, 0);
        CCLayer *menuLayer = [[CCLayer alloc] init];
        [self addChild:menuLayer];
        
        CCMenuItem *scoreItem = [CCMenuItemFont itemFromString:[[NSString alloc] initWithFormat: @"Score: %d", currentScore]];
        CCMenuItem *movesItem = [CCMenuItemFont itemFromString:[[NSString alloc] initWithFormat: @"Moves: %d", moves]];
        
        CCMenuItem *nextLevelItem = [CCMenuItemFont itemFromString:@"NEXT LEVEL"
                                                        target:self
                                                        selector:@selector(nextLevel:)];
        
        CCMenu *menu = [CCMenu menuWithItems: scoreItem, movesItem, nextLevelItem, nil];
        menu.position = ccp(240, 120);
        
        CCLabelTTF *name = [CCLabelTTF labelWithString:@"Name: " fontName:@"Courier" fontSize:32];
        name.position =  ccp(200, 220);
        [self addChild: name];
   
        [menu alignItemsVertically];
        
        [menuLayer addChild: menu];
        
        
    }
    return self;
}
NSString* playersName;
-(BOOL) textFieldShouldReturn:(UITextField *)textField{
    NSLog(@"%@", textField.text);
    playersName = [[NSString alloc] initWithString: textField.text];
    [textField resignFirstResponder];
    return YES;
}

-(void) onEnter{
    [super onEnter];
    
    
    UITextField *textBox = [[UITextField alloc]init];
    textBox.frame = CGRectMake(0.0, 0.0, 120.0, 30.0);
    textBox.backgroundColor = [UIColor whiteColor];
    textBox.delegate = self;
    textBox.font = [UIFont fontWithName:@"Courier" size:24];
    
    wrapper = [CCUIViewWrapper wrapperForUIView:textBox];
    [wrapper setRotation:90];
    wrapper.position = ccp(160,180);
    [self addChild:wrapper];
    

}

-(void) onExit{
    [super onExit];
    [self removeChild:wrapper cleanup:true];
    wrapper = nil;
}

- (void) nextLevel: (id) sender
{

    NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
    NSData *dataRepresentingSavedArray = [currentDefaults objectForKey:@"Scores"];
    NSMutableArray *objectArray = [[NSMutableArray alloc] init];
    if (dataRepresentingSavedArray != nil)
    {
        NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:dataRepresentingSavedArray];
        if (oldSavedArray != nil)
            objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
        else
            objectArray = [[NSMutableArray alloc] init];
    }    
    Score *score = [[Score alloc] init];
    
    score.playerName = playersName;
    score.score = [NSNumber numberWithInt:currentScore];
    score.level = [NSNumber numberWithInt:currentLevel];
    bool scoreForLevelExists;
    
    for (Score *s in objectArray){
        if(s.level == score.level){
            if([s.score intValue]  < [score.score intValue]){
                s.score = score.score;
                s.playerName = score.playerName;
            }
            scoreForLevelExists = true;
        }
    }
    
    if(scoreForLevelExists == false){
        [objectArray addObject:score];
    }
    
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject: objectArray];
           
    currentLevel++;
    NSNumber *lvl = [currentDefaults objectForKey:@"Level"];
    if(lvl == Nil){
        lvl = [[NSNumber alloc] initWithInt:currentLevel];
    }
    else{
        if(currentLevel > [lvl intValue]){            
            lvl = [[NSNumber alloc] initWithInt:currentLevel];
        }
    }
    [currentDefaults setObject:lvl forKey:@"Level"];
    [currentDefaults setObject:data forKey:@"Scores"];
    [currentDefaults synchronize];
    [[CCDirector sharedDirector] replaceScene:[HelloWorldLayer sceneWith:currentLevel]];
}

- (void) dealloc
{
    [super dealloc];
}

@end

